function SVMplotacc(varargin)
%% Build GUI

persistent gui

gui.subjects         = {'AM','HB','JZ','MJ','MP','MR','RW'}; % 'AM','HB','JZ','MJ','MP','MR','RW

gui.nobuttons        = [4 3];       % 1st col: dropdown, 2nd col: edit, 3rd col: checkboxes, 4th col:buttons
gui.buttondistance   = [20 10];
gui.buttonsize       = [120 45];
gui.figuresize       = (gui.buttonsize+gui.buttondistance).*(gui.nobuttons)+gui.buttondistance;
gui.uipositions(:,1) = sort(repmat(round(linspace(gui.buttondistance(1),gui.figuresize(1)-gui.buttondistance(1)-gui.buttonsize(1),gui.nobuttons(1))'),gui.nobuttons(2),1));
gui.uipositions(:,2) = repmat(round(linspace(gui.buttondistance(2),gui.figuresize(2)-gui.buttondistance(2)-gui.buttonsize(2),gui.nobuttons(2))'),gui.nobuttons(1),1);

if ~isempty(varargin) && isa(varargin{1},'double')
    gui.source = varargin{1}; varargin={};
end
if ~isfield(gui,'fid') || ~ishandle(gui.fid);
    gui.fid          = figure(1);
    set(gui.fid,'position',[50 50 gui.figuresize]); else figure(gui.fid);
end
% Builds the gui controls
if ~isfield(gui,'source') || ~ishandle(gui.fid);
gui.h.type            = uicontrol('String','scatter|bar','Style','popupmenu');
gui.h.experiment      = uicontrol('String','SVM Gijs|SVM Bham|Test','Value',1,'Style','popupmenu','Callback',{@SVMplotacc});
gui.h.subjects        = uicontrol('String','placeholder','Style','popupmenu');
gui.h.acctype         = uicontrol('String','normal|normalized|raw','Style','popupmenu'); % accuracy to plot
gui.h.plotchance      = uicontrol('Value',0,'Style','checkbox');
gui.h.axisnames       = uicontrol('Value',1,'Style','checkbox');
gui.h.plotrows        = uicontrol('String',num2str(3),'Style','edit'); 
gui.h.plotcols        = uicontrol('String',num2str(3),'Style','edit'); 
gui.h.start           = uicontrol('Style','pushbutton','String','Go','Callback',{@configuration});
end

gui.experiment        = cellstr(get(gui.h.experiment,'String'));
gui.lfiles            = dir([gui.experiment{get(gui.h.experiment,'Value')} '/' 'MJ/SVM Results/*.mat']); gui.ffnames=gui.lfiles(1).name; for nk=2:length(gui.lfiles); gui.ffnames=[gui.ffnames '|' gui.lfiles(nk).name]; end;
gui.h.loadresult      = uicontrol('String',gui.ffnames,'Value',1,'Style','popupmenu');

%% Set dynamic fields

switch get(gui.h.experiment,'value')
    case 1; gui.subjects         = {'All','LD','TA','MJ','MM','TJ','TJFCD','TK','Specify'};
    case 2; gui.subjects         = {'All','AM','HB','JZ','MJ','MP','MR','RW','Specify'};
    case 3; gui.subjects         = {'TB','MJ','TG'};
end

set(gui.h.subjects,'String',gui.subjects);
% Modifies GUI positions
gui.uifields          = fieldnames(gui.h);
gui.checkboxcount     = 1; n=1; m=1;
while n<=length(gui.uifields);
switch get(gui.h.(char(gui.uifields(n,:))),'Style')
    case 'checkbox'
        set(gui.h.(char(gui.uifields(n,:))),'String',char(gui.uifields(n,:)),'position',[gui.uipositions(m,1) gui.uipositions(m,2)+gui.buttonsize(2)*mod(gui.checkboxcount+1,2)/2 gui.buttonsize(1) gui.buttonsize(2)/2]);
        m=m-mod(gui.checkboxcount,2); gui.checkboxcount = gui.checkboxcount+1;
        if ~isequal(get(gui.h.(char(gui.uifields(n+1,:))),'Style'),'checkbox')&&mod(m,2)~=0; m=m+1; end
    case {'edit'}
        set(gui.h.(char(gui.uifields(n,:))),'position',[gui.uipositions(m,:) gui.buttonsize(1),gui.buttonsize(2)/2]);
        uicontrol('Style','text','String',char(gui.uifields(n,:)),'position',[gui.uipositions(m,1) gui.uipositions(m,2)+gui.buttonsize(2)/2 gui.buttonsize(1) gui.buttonsize(2)/2],'Backgroundcolor',get(gui.fid,'color'))
    case {'popupmenu'}
        set(gui.h.(char(gui.uifields(n,:))),'position',[gui.uipositions(m,:) gui.buttonsize(1),gui.buttonsize(2)/2]);
        uicontrol('Style','text','String',char(gui.uifields(n,:)),'position',[gui.uipositions(m,1) gui.uipositions(m,2)+gui.buttonsize(2)/2 gui.buttonsize(1) gui.buttonsize(2)/2],'Backgroundcolor',get(gui.fid,'color'))
        curstrings = get(gui.h.(char(gui.uifields(n,:))),'String');
        if isequal('Specify',char(curstrings(get(gui.h.(char(gui.uifields(n,:))),'Value'),:))) && isfield(gui,'source') && gui.source==gui.h.(char(gui.uifields(n,:))); 
            gui.s.(char(gui.uifields(n,:))) = specifygui(gui.h.(char(gui.uifields(n,:)))); end
    case 'pushbutton'
        set(gui.h.(char(gui.uifields(n,:))),'position',[gui.uipositions(m,:) gui.buttonsize]);
    otherwise
        set(gui.h.(char(gui.uifields(n,:))),'position',[gui.uipositions(m,:) gui.buttonsize]);
end
    set(gui.h.(char(gui.uifields(n,:))),'Backgroundcolor',get(gui.fid,'color'));
    n=n+1; m=m+1;
end

% Checks for nogui toggle
% if ~isempty(varargin); for n=1:2:length(varargin)
%         if ~isequal(varargin{n},'noGUI')
%     set(gui.h.(char(varargin{n})),'Value',varargin{n+1}); end; end;
% end

gui.nogui = false;
configuration(1,gui);

if sum(strcmp('noGUI',varargin))==1;         % GUI off
    gui.nogui = true;
    set(gui.fid,'Visible','off');
    configuration(gui.h.start,1);
end
end

function configuration(source,event)
%% Set variables
opengl software;

persistent gui

if source == 1;
gui                       =  event;
gui.strings.numberofruns = 0;
else
cfg.uifields        = fieldnames(gui.h);

for n=1:length(gui.uifields);
switch get(gui.h.(char(gui.uifields(n,:))),'Style')
    case 'checkbox'
        cfg.(char(gui.uifields(n,:))) = get(gui.h.(char(gui.uifields(n,:))),'Value');
    case 'edit'
        z=1; remain = {};      remain = get(gui.h.(char(gui.uifields(n,:))),'String');
        while true; 
        [tefield remain]              = strtok(remain); 
        cfg.(char(gui.uifields(n,:)))(z) = str2num(tefield);
        if isempty(remain); break; end; z=z+1; end;
    case 'popupmenu'
        structfields = cellstr(get(gui.h.(char(cfg.uifields(n,:))),'String')); value=get(gui.h.(char(gui.uifields(n,:))),'Value');
        if strcmp('Specify',structfields(value)) 
            cfg.(char(gui.uifields(n,:))) = gui.s.(char(gui.uifields(n,:))); 
        elseif strcmp('All',structfields(value))
            cfg.(char(cfg.uifields(n,:))) = structfields(~strcmp('All',structfields)&~strcmp('Specify',structfields));
        else
            cfg.(char(cfg.uifields(n,:))) = structfields(get(gui.h.(char(cfg.uifields(n,:))),'Value'));
        end
    case 'pushbutton'
        cfg.(char(gui.uifields(n,:))) = get(gui.h.(char(gui.uifields(n,:))),'Value');
    otherwise
        cfg.(char(gui.uifields(n,:))) = get(gui.h.(char(gui.uifields(n,:))),'Value');
end
end


cfg.fid                               = {2,3,4,5,6,7,8,9};
gui.strings.numberofruns              = gui.strings.numberofruns+1;
cfg.numberofruns                      = gui.strings.numberofruns;
startplot(cfg)
end
end

function startplot(cfg)
%% Enable variable argument input
% Enables any input to be modified in a loop, e.g. RunSVM('TimeShift',2000)

cfg.plotcolors    = {[0.8 0.8 0.8],[0 0 0],[0.5 0 0],[0 0.5 1]};
cfg.plotcolor     = cfg.plotcolors {mod(cfg.numberofruns-1,4)+1};

for n=1:length(cfg.subjects);
cfg.timecourses={};
disp(['loading for subject: ' cfg.subjects{n}])
data.(cfg.subjects{n})=open([cfg.experiment{1} '/' cfg.subjects{n} '/SVM Results/' cfg.loadresult{1}]);
    fields  = fieldnames(data.(cfg.subjects{n}).results{end});
    for o=1:length(fields)
        if isa(data.(cfg.subjects{n}).results{end}.(fields{o}),'struct') && not(isequal(fields{o},'accuracy'));
        cfg.timecourses{end+1} = fields{o};
        end
    end

end

for l=1:length(cfg.timecourses);
    
figure(cfg.fid{l});
set (cfg.fid{l},'position', [50 50 1050 618+50], 'Color',[1 1 1]);
for n=1:length(cfg.subjects);
    
    for m=1:length(data.(cfg.subjects{n}).results)
            count=1;
           if isa(data.(cfg.subjects{n}).results{m},'struct')
               Acc.(cfg.subjects{n}).allROIs{m}   = data.(cfg.subjects{n}).results{m}.ROI;
               Acc.(cfg.subjects{n}).accuracies{m}   = data.(cfg.subjects{n}).results{m}.(cfg.timecourses{l}).accuracy.(cfg.acctype{1});
               Acc.(cfg.subjects{n}).(cfg.timecourses{l}).(Acc.(cfg.subjects{n}).allROIs{m})=Acc.(cfg.subjects{n}).accuracies{m};
               count=count+1;
           end
    end
       
    for q=1:length(Acc.(cfg.subjects{n}).allROIs); Acc.(cfg.subjects{n}).ROIs{q}=[Acc.(cfg.subjects{n}).allROIs{q}]; end;

        for p=1:length(Acc.(cfg.subjects{n}).allROIs)
               Acc.(cfg.subjects{n}).meanlist(p)= mean(Acc.(cfg.subjects{n}).(cfg.timecourses{l}).(Acc.(cfg.subjects{n}).allROIs{p}));
               Acc.(cfg.subjects{n}).stdlist(p) = std (Acc.(cfg.subjects{n}).(cfg.timecourses{l}).(Acc.(cfg.subjects{n}).allROIs{p}));
        end
               Acc.(cfg.subjects{n}).chancelevel=mean(data.(cfg.subjects{n}).results{1}.(cfg.timecourses{l}).accuracy.chancelevels); 

switch cfg.type{1}
    case 'scatter';
    if n>cfg.plotcols*(cfg.plotrows-1); cfg.leftcornercorrection = 2; else cfg.leftcornercorrection = 0; end;
    subplot(cfg.plotrows,cfg.plotcols,n+cfg.leftcornercorrection);
    hold on
       errorbar(Acc.(cfg.subjects{n}).meanlist, Acc.(cfg.subjects{n}).stdlist,'color',[0 0 0]);
       title([cfg.subjects{n} ' ' cfg.timecourses{l}]);
       plot(Acc.(cfg.subjects{n}).meanlist,'--d','LineWidth',2,'MarkerEdgeColor','k','MarkerFaceColor',cfg.plotcolor);    
       if cfg.plotchance == 1;
       line([0 length(Acc.(cfg.subjects{n}).meanlist)+1],[Acc.(cfg.subjects{n}).chancelevel Acc.(cfg.subjects{n}).chancelevel],'color',[0 0 0]);
       end
       set(gca,'XColor',get(gcf,'Color'));
       if cfg.axisnames
       textypos=repmat((min(Acc.(cfg.subjects{n}).meanlist)-max(Acc.(cfg.subjects{n}).stdlist)),length(Acc.(cfg.subjects{n}).ROIs),1);
       axis([0,length(Acc.(cfg.subjects{n}).meanlist)+1,0,1]);
       text(1:length(Acc.(cfg.subjects{n}).ROIs),textypos,Acc.(cfg.subjects{n}).ROIs,'HorizontalAlignment','right','rotation',90)
       end
       hold off;
       
    case 'bar'
    subplot('position',cfg.subplotpos); 
    barweb(Acc.(cfg.subjects{n}).meanlist, Acc.(cfg.subjects{n}).stdlist, [], [], [cfg.subjects{n} ' ' cfg.timecourses{l}], [], 'Accuracy', cfg.plotcolor, [], Acc.(cfg.subjects{n}).ROIs, 1, 'axis');
       hold on
       line([0 2],[Acc.(cfg.subjects{n}).chancelevel Acc.(cfg.subjects{n}).chancelevel]);
       hold off
end
end

cfg.info    = ['Filename =' cfg.loadresult{1} ', timecourse = ' cfg.timecourses{l} ', acctype = ' cfg.acctype{1}];
n           = n+1;
cfg.figpos  = get(gcf,'position');
cfg.textbox = uicontrol('Style','text','ForegroundColor',cfg.plotcolor,'BackgroundColor',get(gcf,'Color'),'String',cfg.info,'Position',[0 0.25/cfg.plotrows*(mod(cfg.numberofruns-1,4)) 1/cfg.plotcols 0.25/cfg.plotrows].*[cfg.figpos(3) cfg.figpos(4) cfg.figpos(3) cfg.figpos(4)]);

saveas( gcf,[cfg.experiment{1} '/' 'Results/' char(cfg.info) '.jpg'] );
saveas( gcf,[cfg.experiment{1} '/' 'Results/' char(cfg.info) '.ai' ] );
end
end